package com.camel.base.ei;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camel.base.model.TbMockRequest;
import com.camel.base.model.TbMockResponse;
import com.camel.base.service.TbMockRequestService;
import com.camel.base.service.TbMockResponseService;
import com.camel.core.exceptions.CustomException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/mocks")
public class ThirdPartController {

    @Resource
    private TbMockRequestService<TbMockRequest> requestService;

    @Resource
    private TbMockResponseService<TbMockResponse> responseService;


    @PostMapping("/**")
    public Object api(HttpServletRequest request, @RequestBody JSONObject parmas) {
        String requestURI = request.getRequestURI().substring("/base/mocks".length());

        TbMockRequest mockReq = requestService.getOne(new QueryWrapper<TbMockRequest>().eq("mock_addr", requestURI), false);

        if(ObjectUtils.isEmpty(mockReq)) {
            return BusinessCenterResult.error("|无效的请求地址| mock信息无需记录|");
        }

        List<TbMockResponse> respList = responseService.list(new QueryWrapper<TbMockResponse>().eq("req_id", mockReq.getId()));
        if(CollectionUtils.isEmpty(respList)) {
            return BusinessCenterResult.error("|无效的请求地址： 无响应信息 mock信息无需记录|");
        }

        /**
         * 单个响应 -> 有逻辑 -> 判断逻辑
         * 单个响应 -> 无逻辑 -> 直接返回
          */
        if(respList.size() == 1) {
            TbMockResponse resp = respList.get(0);
            if(StringUtils.isBlank(resp.getSmartLogic())) {
                return parseResult(resp);
            } else {
                if(smartLogicPassed(resp, parmas)) {
                    return parseResult(resp);
                } else {
                    return BusinessCenterResult.success();
                }
            }

        }

        /**
         * 多个响应 -> 不存在无逻辑 -> 判断逻辑
         * 多个响应 -> 存在无逻辑 -> 直接返回
         */
        // 是否有空逻辑
        TbMockResponse nonLogicResp = null;

        for (TbMockResponse tbMockResponse : respList) {
            if(StringUtils.isBlank(tbMockResponse.getSmartLogic())) {
                nonLogicResp = tbMockResponse;
            }
        }

        // 先走完有逻辑
        for (TbMockResponse resp : respList) {
            if(smartLogicPassed(resp, parmas)) {
                return parseResult(resp);
            }
        }

        // 空逻辑兜底
        if(!ObjectUtils.isEmpty(nonLogicResp)) {
            return parseResult(nonLogicResp);
        }

        return BusinessCenterResult.success("|无效的请求地址： 无响应信息 mock信息无需记录|");

    }

    public Object parseResult(TbMockResponse resp) {
        if(resp.getAllOut().equals(1)) {
            return parseStrToResult(resp.getRespStr());
        }
        return BusinessCenterResult.success(resp.getRespCode(), resp.getRespMsg(), parseStrToResult(resp.getRespStr()));
    }

    public Object parseStrToResult(String str) {
        if(StringUtils.isBlank(str)) {
            return str;
        }
        try {
            return JSON.parse(str);
        } catch (Exception e) {
            return str;
        }
    }

    /**
     * 判断微逻辑是否通过
     * @param resp
     * @param params
     * @return
     */
    public boolean smartLogicPassed(TbMockResponse resp, JSONObject params) {
        String smartLogic = resp.getSmartLogic();
        if(StringUtils.isBlank(smartLogic)) {
            return false;
        }
        String[] split = smartLogic.split(";");
        for (String s : split) {
            if(!s.contains("=")) {
                throw new CustomException("|微逻辑 <"+ s +"> 不符合规范： mock信息无需记录|");
            }
            String[] split1 = s.split("=", 2);
            String value = params.getString(split1[0]);
            return split1[1].equals(value);
        }

        return false;

    }


    /**
     * 执法记录仪发送相关命令
     */
    @PostMapping("/assetmgtForwarder/command")
    public AjaxResult assetmgtForwarderCommand(@RequestBody JSONObject jsonObject) {
        return new AjaxResult("iot.api.device.command.post.service.sendMessage.success", "");
    }

    /**
     * 人工智能 - 更新作业计划
     */
    @PostMapping("/rmcp-ai/workplan/updateDayPlan")
    public AjaxResult workplanUpdateDayPlan(@RequestBody JSONObject jsonObject) {
        return new AjaxResult("1", "");
    }

    /**
     * 人工智能 - 更新告警接口
     */
    @PostMapping("/rmcp-ai/aiAlert/updateAiAlert")
    public AjaxResult aiAlertUpdateAiAlert(@RequestBody JSONObject jsonObject) {
        return new AjaxResult("1", "");
    }
//
//
//    /**
//     * 更新调取票接口
//     */
//    @PostMapping("/ticketcommon/openApi/ticket/updateTicketByWeekPlan")
//    public BusinessCenterResult updateTicketByWeekPlan(@RequestBody JSONObject jsonObject) {
//        return BusinessCenterResult.success();
//    }
//
//
//
//    /**
//     * token换用户
//     */
//    @PostMapping("/baseCenter/oauth2/user/token")
//    public BusinessCenterResult userFromToken(@RequestBody JSONObject jsonObject) {
//        JSONObject object = FileUtils.readJsonFile("userFromToken.json");
//        return BusinessCenterResult.success(object);
//    }
//
//    /**
//     * 查询i国网工号对应工号，可以选择是否带参数，如果不带参数表示全查
//     */
//    @PostMapping("/baseCenter/userOrgService/getUserIgw")
//    public BusinessCenterResult getUserIgw(@RequestBody JSONObject jsonObject) {
//        JSONObject object = FileUtils.readJsonFile("userIgw.json");
//        return BusinessCenterResult.success(object);
//    }
//
//
//
//
//    /**
//     * PC端校验TOKEN是否有效
//     */
//    @PostMapping("/baseCenter/oauth2/token/validation")
//    public BusinessCenterResult tokenValidation(@RequestBody JSONObject jsonObject) {
//        return BusinessCenterResult.success();
//    }
//
//    /**
//     * PC端获取正常ACCESSTOKEN
//     */
//    @PostMapping(value = "/baseCenter/oauth2/accessToken")
//    public BusinessCenterResult tokenAccessToken() {
//        JSONObject object=new JSONObject();
//        object.put("access_token","123");
//        return BusinessCenterResult.success(object);
//    }
//
//
//
//    /**
//     * 获取设备所在行政地理区域
//     */
//    @PostMapping("/geoCenter/gisProxyService/regeo")
//    public BusinessCenterResult regeo(@RequestBody JSONObject jsonObject) {
//        return BusinessCenterResult.success();
//    }
//
//
//
//    /**
//     * 用户权限
//     */
//    @PostMapping("/baseCenter/privService/privs/userNo")
//    public BusinessCenterResult privsUserNo(@RequestBody JSONObject jsonObject) {
//        JSONObject object = FileUtils.readJsonFile("privUserNo.json");
//        JSONArray key = object.getJSONArray("key");
//        return BusinessCenterResult.success(key);
//    }
//
//    @PostMapping("/baseCenter/userOrgService/orgs/orgNo")
//    public BusinessCenterResult org(@RequestBody JSONObject jsonObject) {
//        String orgNo = jsonObject.getString("orgNo");
//        // JSON需要内网获取
//        JSONObject object = FileUtils.readJsonFile("getCrewListByEnterpriseId.json");
//        BusinessCenterResult success = BusinessCenterResult.success(object);
//        return success;
//    }

}
